package pl.un4giv3n.mightvsmagic.action;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.entity.Message;
import pl.un4giv3n.mightvsmagic.entity.User;

/**
 * @author andrzejewskia
 * sends message to user
 */
public class SendMessageAction extends PersistenceAction{

	private static final long serialVersionUID = 1L;
	
	private String subject;
	private String message;
	private String reciverLogin;
	
	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		User user = getSessionUser(entityManager);
		if(user == null){
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}else{
			Query query = entityManager.createNamedQuery("find.user.by.login");
			query.setParameter("login", reciverLogin);
			List resultList = query.getResultList();
			if(resultList == null || resultList.isEmpty()){
				addActionError("Nie znaleziono odbiorcy o podanej nazwie");
				entityManager.close();
				return INPUT;
			}else{
				User reciver = (User) resultList.get(0);
				Message msg = new Message(subject, message, user, reciver);
				EntityTransaction transaction = entityManager.getTransaction();
				transaction.begin();
				entityManager.persist(msg);
				entityManager.flush();
				transaction.commit();
				entityManager.close();
			}
		}
		return SUCCESS;
	}
	
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getReciverLogin() {
		return reciverLogin;
	}
	public void setReciverLogin(String receiverLogin) {
		this.reciverLogin = receiverLogin;
	}
	
}